package com.bungarus.rm.controller;

import com.bungarus.error.BungarusError;
import com.bungarus.rm.model.IDMakerScope;
import com.bungarus.rm.service.MsgIDScopeService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by tang on 2019/1/13.
 */
@RestController
public class MsgIDMakerScopeController extends BungarusController{
    Logger logger = Logger.getLogger(MsgIDMakerScopeController.class);

    private static final String ID_DELIMITER = ",";
    private MsgIDScopeService scopeService;

    @Autowired
    public MsgIDMakerScopeController(MsgIDScopeService scopeService) {
        this.scopeService = scopeService;
    }

    @GetMapping("/id-scopes/nodes/")
    public String getMsgIDScope0() throws Exception {
        throw new IllegalArgumentException(buidErrorString(404, "node id required."));
    }

    @GetMapping("/id-scopes/nodes/{id}")
    @ResponseStatus(HttpStatus.OK)
    public IDMakerScope getMsgIDScope(@PathVariable("id") String id) {
        /*pattern of node id is <code>clusterid,nodeid</code> */
        try {
            String[] ids = StringUtils.tokenizeToStringArray(id, ID_DELIMITER);
            if(ids.length != 2) {
                throw new IllegalArgumentException(buidErrorString(405, "invalid input type."));
            }
            int clusterId = Integer.parseInt(ids[0]);
            int nodeId = Integer.parseInt(ids[1]);
            if(clusterId < 0 || nodeId < 0) {
                throw new IllegalArgumentException(buidErrorString(405, "all ids must be positive."));
            }

            return scopeService.requestAScope(Integer.parseInt(ids[0]), Integer.parseInt(ids[1])).get();

        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException(buidErrorString(405, "invalid input type."));
        }
    }

    private String buidErrorString(int code, String errorMsg){
        BungarusError error = BungarusError.newBuilder()
                .code(code)
                .message(errorMsg)
                .build();
        String errorJosn = null;
        try {
            errorJosn = new ObjectMapper().writeValueAsString(error);
        }
        catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return errorJosn;
    }
}
